/*
 * @Author: Dorange.Wang
 * @Date: 2021-11-22 09:25:21
 * @LastEditors: your name
 * @LastEditTime: 2021-11-22 10:15:14
 * @Description: file content
 */
import store from '@/store'
import Vue from 'vue'

class PermUtil {
  static init() {
    Vue.directive('permission', {
      bind: async function (el, binding) {
        if (process.env.VUE_APP_USER === 'ADMIN') return

        el.classList.add('permission__button--hidden')
        const { arg, value } = binding
        const pageKey = arg ? arg.split('__')[0] : value[0].split('__')[0]
        let blackButtonsPromise = store.getters.blackButtonsPromise[pageKey]
        if (!blackButtonsPromise) {
          store.dispatch('loadBlackButtons', pageKey)
          blackButtonsPromise = store.getters.blackButtonsPromise[pageKey]
        }

        //新加 或逻辑
        let actionNames = null
        if (!arg && value && Array.isArray(value)) {
          actionNames = value
        }

        const res = await blackButtonsPromise
        const { buttons } = res

        if (actionNames) {
          if (!isNotContainOne(buttons, actionNames)) {
            (el.parentNode && el.parentNode.removeChild(el)) || el.classList.add('permission__button--hidden')
          } else {
            el.classList.remove('permission__button--hidden')
          }
        } else {
          if (buttons.includes(arg)) {
            (el.parentNode && el.parentNode.removeChild(el)) || el.classList.add('permission__button--hidden')
          } else {
            el.classList.remove('permission__button--hidden')
          }
        }
      }
    })
  }
}
/**
 * childArr中是否有至少一个元素不存在于parentArr
 * @param {*} parentArr
 * @param {*} childArr
 */
function isNotContainOne(parentArr, childArr) {
  for (let i = childArr.length - 1; i >= 0; i--) {
    if (!parentArr.includes(childArr[i])) {
      return true
    }
  }
  return false
}
export default PermUtil
